//引入axios的核心库及内部封装好的数据类型
import axios, { Axios, AxiosInstance, AxiosRequestConfig } from 'axios'
//引入封装好的接口类型
import { ResultData } from './interface'
// import { useRouter } from 'vue-router'
// let router = useRouter()
import router from '../router'

import querystring from 'querystring'
//定义的配置对象
let config = {
    baseURL: '/api'
}

//定义一个类 用于封装  请求方法以及拦截器
class Http {
    http: AxiosInstance
    //构造器
    constructor(config: AxiosRequestConfig) {
        //重新实例化
        this.http = axios.create(config)
        //请求拦截器
        this.http.interceptors.request.use(req => {
            // console.log(req, 'req');
            if (req.url !== "userlogin") {
                //添加token
                req.headers.authorization = sessionStorage.getItem('userinfo') ? JSON.parse(sessionStorage.getItem('userinfo') + '').token : null
            }
            return req
        });
        //响应拦截器
        this.http.interceptors.response.use(res => {
            if (res.data.msg == "请设置请求头,并携带验证字符串") {
                alert(res.data.msg)
                //强制跳转到登录页
                router.push('/login')
            } else if (res.data.msg == "登录已过期或访问权限受限") {
                alert(res.data.msg)
                router.push('/login')
            } else {
                return res.data
            }
        })
    }


    get<T>(url: string, params?: object): Promise<ResultData<T>> {
        return this.http.get(url, {
            params
        })
    }
    post<T>(url: string, params?: any, isFile: boolean = false): Promise<ResultData<T>> {

        let data: any = {}
        if (isFile) {
            //有文件
            data = new FormData()
            console.log(data)
            for (const [key, val] of Object.entries(params)) {
                data.append(key, val)
            }

        } else {
            data = querystring.stringify(params)
        }
        return this.http.post(url, data)
    }
}

//实例化类并导出
export default new Http(config)